import { useQuery } from '@tanstack/vue-query'
import { type MaybeRef, computed, isRef } from 'vue'
import type { GetReportReportQueryKey, SearchReportQueryKey } from './types'
import { ApiGetReport, ApiSearchReport } from '.'

export function useGetReportQueryKey(id: MaybeRef<number>): MaybeRef<GetReportReportQueryKey> {
  return isRef(id) ? computed(() => ['get', 'reports', id.value]) : ['get', 'reports', id]
}
export function useGetReport<T extends object>(
  id: MaybeRef<number>,
  enabled: MaybeRef<boolean> = true
) {
  return useQuery({
    enabled,
    staleTime: 60_000,
    queryKey: useGetReportQueryKey(id),
    queryFn: ({ queryKey: [, , id] }) => ApiGetReport(id),
    select: ({ data: { content, ...rest } }) => ({
      ...rest,
      content: JSON.parse(content) as T
    })
  })
}

export function useSearchReportQueryKey(
  query: MaybeRef<SearchReportQueryKey[2]>
): MaybeRef<SearchReportQueryKey> {
  return isRef(query) ? computed(() => ['get', 'reports', query.value]) : ['get', 'reports', query]
}
export function useSearchReport(query: MaybeRef<SearchReportQueryKey[2]>) {
  return useQuery({
    staleTime: 60_000,
    queryKey: useSearchReportQueryKey(query),
    queryFn: ({ queryKey: [, , query] }) => ApiSearchReport(query),
    select: ({ data }) => data
  })
}
